﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';

class ChangePasswordLogic extends GetxController {
  final oldPasswordController = TextEditingController();
  final newPasswordController = TextEditingController();
  final confirmPasswordController = TextEditingController();

  final showOldPassword = false.obs;
  final showNewPassword = false.obs;
  final showConfirmPassword = false.obs;

  @override
  void onClose() {
    oldPasswordController.dispose();
    newPasswordController.dispose();
    confirmPasswordController.dispose();
    super.onClose();
  }

  /// 修改密码
  Future<void> changePassword() async {
    final oldPassword = oldPasswordController.text.trim();
    final newPassword = newPasswordController.text.trim();
    final confirmPassword = confirmPasswordController.text.trim();

    // 验证输入
    if (oldPassword.isEmpty) {
      Toast.show( '请输入旧密码');
      return;
    }

    if (newPassword.isEmpty) {
      Toast.show('请输入新密码');
      return;
    }

    if (newPassword.length < 6 || newPassword.length > 20) {
      Toast.show( '新密码长度应为6-20位');
      return;
    }

    if (confirmPassword.isEmpty) {
      Toast.show( '请确认新密码');
      return;
    }

    if (newPassword != confirmPassword) {
      Toast.show( '两次输入的新密码不一致');
      return;
    }

    if (oldPassword == newPassword) {
      Toast.show( '新密码不能与旧密码相同');
      return;
    }

    try {
      final response = await DefaultApi().resetPwdPut(
        oldPassword: oldPassword,
        newPassword: newPassword,
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        Toast.show( '密码修改成功，请重新登录');
        // 返回到上一页
        Get.back();
        // TODO: 可以在这里添加退出登录的逻辑
      } else {
        final msg = response?['msg'] ?? '密码修改失败';
        Toast.show(msg);
      }
    } catch (e) {
      print('修改密码失败: $e');
      Toast.show('修改密码失败：$e');
    }
  }
}
